//
//  ZZVipController.m
//  QQplayground
//
//  Created by zhangxy on 2018/8/16.
//  Copyright © 2018年 zhang. All rights reserved.
//

#import "ZZVipController.h"
#import "ZZPayView.h"


#import "ZZVipCell.h"
#define cellIdentifier @"ZZVipCell"

#import "ZZVipPayController.h"

@interface ZZVipController (){
    BOOL isShowPayResult;
    int count;
}

@property(nonatomic,strong) NSMutableArray *listArray;

@property(nonatomic,strong) UITableView *listTable;

@property(nonatomic,strong) UIButton *btnVip;
@property(nonatomic,strong) UILabel *labVipValidate;


@end

@implementation ZZVipController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.navigationItem.title = @"Q友会员";
    
    [self setNavigationBar];
    
    self.navigationController.navigationBarHidden = NO;
    
    [self.view setBackgroundColor:UIColorFromRGB(BgSystemColor)];
    [self createTableView];
    
    [self createBottomView];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self->_listArray addObjectsFromArray:@[@[@{@"title":@"身份标识",@"desc":@"如影随行 尊贵身份",@"icon":@"ic_vip_intro1",@"code":@"1"},
                                                  @{@"title":@"红色昵称",@"desc":@"尊贵的红 与众不同",@"icon":@"ic_vip_intro2",@"code":@"2"},
                                                  @{@"title":@"广告过滤",@"desc":@"告别广告 体验升级",@"icon":@"ic_vip_intro2",@"code":@"3"},
                                                  ],
                                                @[@{@"title":@"背景装扮",@"desc":@"全屏背景 个性展示",@"icon":@"ic_vip_intro1",@"code":@"4"},
                                                  @{@"title":@"留言置顶",@"desc":@"朋友很多 独偏爱你",@"icon":@"ic_vip_intro2",@"code":@"5"}]]];
        
        [self.listTable reloadData];
    });
    
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [self loadBegin];
    
    //返回微信支付的结果
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(WXPayResult:) name:@"WXPayResult" object:nil];
}

-(void)WXPayResult:(NSNotification *) info{
    
    NSDictionary *dict = info.object;
    
    [self checkResultStatus:dict];
}
/**
 {
 "attr_id" = 1;
 "goods_sn" = gs20180806211015100001;
 "session_uid" = 2262561;
 sign = 9fccebd3d96306ac2d5a576b1f440d96;
 ts = 1537186360;
 udid = "A7E7800C-BF5A-4699-BD24-70A20D4AFD44";
 ver = "3.0.0";
 }
 */
-(void)checkResultStatus:(NSDictionary *) dict{
    if([dict[@"code"] intValue] == 0 && isShowPayResult){
        isShowPayResult = NO;
        
        if(convertToString(dict[@"message"]).length > 0){
            [PopUtil showMessage:dict[@"message"]];
            [self loadBegin];
        }
        
        if(convertToString(dict[@"order_no"]).length > 0){
            [MBProgressHUD showHUDAddedTo:self.view animated:YES];
            count = 0;
            [self searchOrderNo:convertToString(dict[@"order_no"])];
        }
    }else{
        [PopUtil showMessage:dict[@"message"]];
    }
}

//查询订单是否成功
-(void)searchOrderNo:(NSString *)orderNo{
    DLog(@"searchOrderNo");
    
    count = count + 1;
    [NetworkUtil POST:API_GetOrderiscomplete parameters:@{@"order_no":convertToString(orderNo)} success:^(id responseObject, NSDictionary *dict) {
        if([dict[@"status"] intValue] == 1){
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            [self openVipAPI:orderNo];
        }else{
            if(count <= 5){
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [self searchOrderNo:orderNo];
                });
            }else{
                [MBProgressHUD hideHUDForView:self.view animated:YES];
            }
        }
    } failure:^(NSError *error, NSString *message) {
        NSLog(@"message:%@", message);
        [PopUtil showMessage:message];
        if(count <= 5){
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self searchOrderNo:orderNo];
            });
        }else{
            [MBProgressHUD hideHUDForView:self.view animated:YES];
        }
    }];
}

// 根据订单号去开通VIP
-(void)openVipAPI:(NSString *)order{
    NSLog(@"openVipAPI");
    [NetworkUtil POST:API_OpenMyVip parameters:@{@"session_uid":[UserUtil getUser].user_id,@"order_no":convertToString(order)} success:^(id responseObject, NSDictionary *dict) {
        [self loadBegin];
    } failure:^(NSError *error, NSString *message) {
        [[AlertUtil shareInstance] showAlert:@"提醒" message:message cancelTitle:@"我知道了" titleArray:nil viewController:self confirm:^(NSInteger buttonTag) {
            
        }];
    }];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    self.navigationController.navigationBarHidden = NO;
}


-(void)createTableView{
    _listArray = [[NSMutableArray alloc] init];
    
    _listTable=[self.view createTableView:self cell:cellIdentifier];
    [_listTable setFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height - 74)];
    [_listTable setBackgroundColor:UIColorFromRGB(TextWhiteColor)];
    
    if (iOS7) {
        _listTable.backgroundView = nil;
    }
    UIView *footer =[ [UIView alloc]init];
    footer.backgroundColor = [UIColor clearColor];
    [_listTable setTableFooterView:footer];
    
    [_listTable setSeparatorColor:LINE_COLOR];
    [_listTable setSeparatorStyle:UITableViewCellSeparatorStyleSingleLine];
    
    _listTable.tableHeaderView = [self createHeaderView];
    _listTable.tableFooterView = [self createFooterView];
    
    [self setTableSeparatorInset];
}

-(void)openVip:(UIButton *) btn{
    NSLog(@"开通vip---------zzvip");
    isShowPayResult = YES;
    ZZPayView *pay = [[ZZPayView alloc] initWithShareType:self result:^(int code, NSDictionary *dict) {
        //进入确认支付页面的时候进行调用
        NSLog(@"code:%d------%@", code, dict);
        [self checkResultStatus:dict];
    }];
    [pay show];
}



-(void)loadBegin{
    NSLog(@"调用我----------");
    [NetworkUtil POST:API_GetMyvipdetail parameters:@{@"session_uid":[UserUtil getUser].user_id,@"page_size":@"30"} success:^(id responseObject, NSDictionary *dictionary) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        NSDictionary *dict = dictionary[@"data"][@"vip_info"];
        if(dict){
            [_labVipValidate setText:[NSString stringWithFormat:@"到期时间:%@",dateTransformDateString(@"yyyy/MM/dd", convertToString(dict[@"vip_end_time"]))]];
            [_btnVip setImage:[UIImage imageNamed:@"vip"] forState:0];
        }else{
            [_labVipValidate setText:dictionary[@"msg"]];
            [_btnVip setImage:[UIImage imageNamed:@"开通会员"] forState:0];
        }

    } failure:^(NSError *error, NSString *message) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
    }];
}

#pragma mark UITableView delegate Start
// 返回section数
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}

// 返回section高度
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return  64;
}

// 返回section 的View
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 64)];
    
    UILabel *label = [self createLabel];
    [label setFrame:CGRectMake(0, 30, ScreenWidth, 24)];
    [label setTextAlignment:NSTextAlignmentCenter];
    [label setFont:FontSeventeen];
    [headerView addSubview:label];
    if(section == 0){
        [label setText:@"身份特权"];
    }else{
        [label setText:@"功能特权"];
    }
    return headerView;
}

// 返回section下得行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if(_listArray.count == 0){
        return 0;
    }
    NSArray *arr = _listArray[section];
    return arr.count;
}

// cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    ZZVipCell *cell = (ZZVipCell*)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil) {
        cell = [[ZZVipCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    }
    NSArray *arr = _listArray[indexPath.section];
    
    [cell dataToView:arr[indexPath.row]];
    return cell;
}



// 是否显示删除功能
-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
    return NO;
}

// 删除清理数据
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    editingStyle = UITableViewCellEditingStyleDelete;
}


// table 行的高度
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //    return 70.0f;
    UITableViewCell *cell = [self tableView:tableView cellForRowAtIndexPath:indexPath];
    return cell.frame.size.height;
}

// table 行的点击事件
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    NSArray *arr = _listArray[indexPath.section];
    
    NSDictionary *entity=arr[indexPath.row];
    
    ZZVipPayController *vc = [[ZZVipPayController alloc] init];
    vc.code = [entity[@"code"] intValue];
    vc.listArray = _listArray;
    [vc setVipPayResult:^(int code, NSString *message) {
        [self checkResultStatus:@{@"code":convertIntToString(code),@"message":message}];
    }];
    [self openPushVC:vc];

}

//设置分割线间距
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.row < _listArray.count){
        UIEdgeInsets inset = UIEdgeInsetsMake(0, 10, 0, 0);
        if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
            [cell setSeparatorInset:inset];
        }
        
        if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
            [cell setLayoutMargins:inset];
        }
    }else{
        UIEdgeInsets inset = UIEdgeInsetsMake(0, ScreenWidth, 0, 0);
        if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
            [cell setSeparatorInset:inset];
        }
        
        if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
            [cell setLayoutMargins:inset];
        }
    }
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    
    CGFloat sectionHeaderHeight = 64;
    
    if (scrollView.contentOffset.y<=sectionHeaderHeight&&scrollView.contentOffset.y>=0) {
        
        scrollView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0, 0);
        
    } else if (scrollView.contentOffset.y>=sectionHeaderHeight) {
        
        scrollView.contentInset = UIEdgeInsetsMake(-sectionHeaderHeight, 0, 0, 0);
        
    }
    
}
-(void)viewDidLayoutSubviews{
    [self setTableSeparatorInset];
}
#pragma mark UITableView delegate end

/**
 *  设置UITableView分割线空隙
 */
-(void)setTableSeparatorInset{
    UIEdgeInsets inset = UIEdgeInsetsMake(0, 10, 0, 0);
    if ([_listTable respondsToSelector:@selector(setSeparatorInset:)]) {
        [_listTable setSeparatorInset:inset];
    }
    
    if ([_listTable respondsToSelector:@selector(setLayoutMargins:)]) {
        [_listTable setLayoutMargins:inset];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


-(UIView *) createHeaderView{
    UIView *header = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 130)];
    
    UIImageView *imgTop = [[UIImageView  alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 86)];
    [imgTop setBackgroundColor:UIColorFromRGB(BgTitleColor)];
    [header addSubview:imgTop];
    
    UIImageView *imgC = [[UIImageView  alloc] initWithFrame:CGRectMake(20, 17, ScreenWidth - 40, 104)];
    [imgC setBackgroundColor:UIColor.whiteColor];
    imgC.layer.cornerRadius = 8.0f;
    imgC.layer.masksToBounds = YES;
    [header addSubview:imgC];
    
    UIImageView *imgAvatar = [[UIImageView  alloc] initWithFrame:CGRectMake(35, 37, 65, 65)];
    [imgAvatar setBackgroundColor:UIColor.whiteColor];
    imgAvatar.layer.cornerRadius = 32.5f;
    imgAvatar.layer.masksToBounds = YES;
    [imgAvatar sd_setImageWithURL:[NSURL URLWithString:convertToString([UserUtil getUser].user_avatar)] placeholderImage:[UIImage imageNamed:@"default_image"]];
    [header addSubview:imgAvatar];
    
    
    UILabel *labName = [[UILabel alloc] initWithFrame:CGRectMake(115, 46, ScreenWidth - 115 - 45, 24)];
    [labName setFont:FontSeventeen];
    [labName setText:[UserUtil getUser].user_name];
    [labName setTextColor:UIColorFromRGB(TextSizeOneColor)];
    [header addSubview:labName];
    
    [self autoWidthOfLabel:labName with:24];
    CGRect f = labName.frame;
    
    [imgAvatar setFrame:CGRectMake( (ScreenWidth - 65 - f.size.width - 5)/2, 37, 65, 65)];
    f.origin.x = CGRectGetMaxX(imgAvatar.frame) + 5;
    labName.frame = f;
    
    
    _labVipValidate = [self createLabel];
    [_labVipValidate setFrame:CGRectMake(f.origin.x, CGRectGetMaxY(f) + 5, ScreenWidth - 115 - 45, 21)];
    [_labVipValidate setFont:FontThirteen];
    [_labVipValidate setTextColor:UIColorFromRGB(TextSizeEightColor)];
    
    [header addSubview:_labVipValidate];
    
    
    _btnVip = [self createButton];
    [_btnVip setFrame:CGRectMake(CGRectGetMaxX(f) + 5, f.origin.y + 3 ,62 , 18)];
    [_btnVip setImage:[UIImage imageNamed:@"开通会员"] forState:0];
    [header addSubview:_btnVip];
    
    return header;
}


-(void) createBottomView{
    UIView *header = [[UIView alloc] initWithFrame:CGRectMake(0, ScreenHeight - 74 - NavBarHeight, ScreenWidth, 74)];
    
    UIButton *btnOpen = [self createButton];
    [btnOpen setFrame:CGRectMake(10,10 ,ScreenWidth - 20 , 44)];
    if([UserUtil getUser].is_vip){
        [btnOpen setTitle:@"续费会员" forState:0];
    }else{
        [btnOpen setTitle:@"开通会员" forState:0];
    }
    [btnOpen setBackgroundColor:UIColorFromRGB(BgTitleColor)];
    btnOpen.layer.cornerRadius = 6.0f;
    btnOpen.layer.masksToBounds = YES;
    [btnOpen addTarget:self action:@selector(openVip:) forControlEvents:UIControlEventTouchUpInside];
    [header addSubview:btnOpen];
    
    [self.view addSubview:header];
}

-(UIView *) createFooterView{
    UIView *header = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 60)];
    
    UILabel *labName = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 60)];
    [labName setFont:FontSeventeen];
    [labName setText:@"更多特权 敬请期待"];
    [labName setTextAlignment:NSTextAlignmentCenter];
    [labName setTextColor:UIColorFromRGB(TextSizeOneColor)];
    [header addSubview:labName];
    
    return header;
}

- (CGSize )autoWidthOfLabel:(UILabel *)label with:(CGFloat )width{
    //Calculate the expected size based on the font and linebreak mode of your label
    // FLT_MAX here simply means no constraint in height
    CGSize maximumLabelSize = CGSizeMake(FLT_MAX, width);
    
    CGSize expectedLabelSize = [label sizeThatFits:maximumLabelSize];
    
    //adjust the label the the new height.
    CGRect newFrame = label.frame;
    newFrame.size.width = expectedLabelSize.width;
    label.frame = newFrame;
    [label updateConstraintsIfNeeded];
    
    return expectedLabelSize;
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
